<template>
    <div>
        <div class="n-layout-page-header">
            <n-card :bordered="false" title="职位管理"></n-card>
        </div>
        <n-card :bordered="false" class="mt-4 proCard">
            <BasicTable :columns="positionColumns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
                :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :bordered="false"
                allow-checking-not-loaded @load="onLoad">
                <template #tableTitle>
                    <n-button type="primary" :on-click="handleEdit.bind(null, {}, 1)">
                        <template #icon>
                            <n-icon>
                                <PlusOutlined />
                            </n-icon>
                        </template>
                        添加职位
                    </n-button>
                </template>
                <template #action>
                    <TableAction />
                </template>
            </BasicTable>
        </n-card>

        <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle">
            <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
                <n-form-item label="职位名称" path="positionName">
                    <n-input maxlength="100" show-count placeholder="请输入职位名称" v-model:value="fromValues.positionName" />
                </n-form-item>
                <n-form-item label="职位级别" path="level">
                    <n-input-number style="width: 100%;" placeholder="请输入职位级别" v-model:value="fromValues.level" />
                </n-form-item>
                <n-form-item label="职位代号" path="positionCode">
                    <n-select v-model:value="fromValues.positionCode" placeholder="请选择职位代号" :options="positionCodeList" />
                </n-form-item>
                <n-form-item label="职位说明" path="positionDesc">
                    <n-input maxlength="300" show-count type="textarea" :autosize="{
                        minRows: 3,
                        maxRows: 5
                    }" v-model:value="fromValues.positionDesc" filterable placeholder="请输入描述" />
                </n-form-item>
            </n-form>
            <div style="justify-content: end;display: flex;">
                <n-space>
                    <n-button ghost icon-placement="left" @click="handleCloseModel">
                        取消
                    </n-button>
                    <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
                </n-space>
            </div>
        </n-modal>
    </div>
</template>
  
<script lang="ts" setup>
import { ref, h, reactive, unref, onMounted } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { positionColumns } from './columns';
import { positionPage, childrenList, savePosition, updatePosition, removePosition, positionCodePage } from '@/api/system/position';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
const message = useMessage();
const dialog = useDialog();
const formBtnLoading = ref(false);
const actionRef = ref();
const editTitle = ref('');
const isAdd = ref(1);
const showModal = ref(false);
const formRef: any = ref(null);
const positionCodeList = ref<any>([]);
const defaultValueRef = () => ({
    id: null,
    /**父级ID*/
    parentId: 0,
    /**职位名称*/
    positionName: '',
    /**职位说明*/
    positionDesc: '',
    /**职位级别*/
    level: 1,
    /**职位代号*/
    positionCode: '',
});
let fromValues = reactive(defaultValueRef());
const rules: FormRules = {
    positionName: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入职位名称',
    },
    level: {
        type: 'number',
        required: true,
        message: '请输入级别',
        trigger: ['blur', 'change'],
    },
    positionCode: {
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择职位代号',
    },
};
const loadDataTable = async (res: any) => {
    return await positionPage(res);
};
/**
 * 子集数据查询
 * @param row 
 */
const onLoad = async (row: Record<string, unknown>) => {
    const data = await childrenList({ parentId: row.id });
    return new Promise<void>((resolve) => {
        row.children = data;
        resolve();
    })
}
const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
        return h(TableAction as any, {
            style: 'text',
            actions: createActions(record),
        });
    },
});

function createActions(record) {
    return [
        {
            label: '新增',
            type: 'success',
            icon: PlusOutlined,
            onClick: handleEdit.bind(null, record, 3),
            ifShow: () => {
                return true;
            },
            //auth: ['basic_list'],
        },
        {
            label: '编辑',
            type: 'primary',
            icon: EditOutlined,
            onClick: handleEdit.bind(null, record, 2),
            ifShow: () => {
                return true;
            },
            //auth: ['basic_list'],
        },
        {
            label: '删除',
            type: 'error',
            // 配置 color 会覆盖 type
            color: 'red',
            icon: DeleteOutlined,
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            //auth: ['basic_list'],
        },
    ];
}
function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
}

function reloadTable() {
    actionRef.value.reload();
}
/**
 * 新增，编辑，新增子节点
 * @param record 
 * @param addStatus 
 */
function handleEdit(record: Recordable, addStatus: number) {
    showModal.value = true;
    isAdd.value = addStatus;
    if (addStatus === 1) {
        editTitle.value = `新增职位`;
    }
    if (addStatus === 2) {
        editTitle.value = `编辑 ${record.positionName}`;
        fromValues = Object.assign(fromValues, record);
    }
    if (addStatus === 3) {
        editTitle.value = `新增 ${record.positionName}子节点`;
        fromValues = Object.assign(fromValues, { parentId: record.id });
    }
}
function resetFrom() {
    formRef.value.restoreValidation();
    fromValues = Object.assign(unref(fromValues), defaultValueRef());
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
    e.preventDefault();
    formRef.value.validate(async (errors) => {
        if (!errors) {
            formBtnLoading.value = true;
            let data: any = isAdd.value === 2 ? await updatePosition(fromValues) : await savePosition(fromValues);
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.mesg + '-' + resultMsg);
                formBtnLoading.value = false;
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.mesg);
                showModal.value = false;
                formBtnLoading.value = false;
                resetFrom();
                reloadTable();
            }
        } else {
            message.error('请填写完整信息');
        }
    });
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
    resetFrom();
    showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
    dialog.warning({
        title: '警告',
        content: `确定删除${record.positionName}吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const data = await removePosition({ id: record.id });
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.mesg + '-' + resultMsg);
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.mesg);
                showModal.value = false;
                reloadTable();
            }
        },
    })
}
onMounted(async () => {
    const data = await positionCodePage({ current: 1, size: 30 });
    const arry = data.records.map(item => ({ label: item.codeName, value: item.positionCode }));
    positionCodeList.value = arry;
})
</script>
  
<style lang="less" scoped></style>
  